import { getBannerApi, removeBannerApi } from '@/services/banner';
import { PageContainer } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Button, Image, Popconfirm, Table, message } from 'antd';
import { useState } from 'react';

interface BannerItem {
  bannerid: string;
  img: string;
  alt: string;
  link: string;
}

const Index: React.FC = () => {
  // const [dataSource, setDataSource] = useState<BannerItem[]>([]);
  const [messageApi, contextHolder] = message.useMessage();
  const [count, setCount] = useState(1);

  const columns = [
    {
      title: '图片',
      dataIndex: 'img',
      // 如果不加render属性，默认是显示dataIndex的值，加了之后，就会显示render的返回值
      // render可以接受两个参数，第一个是当前行的值，第二个是当前行的数据
      render(text: string) {
        // return <img src={text} alt="" style={{ width: '150px' }} />;
        return (
          <Image
            width={200}
            src={text}
            placeholder={<Image preview={false} src={text} width={200} />}
          />
        );
      },
    },
    {
      title: '提示',
      dataIndex: 'alt',
    },
    {
      title: '链接',
      dataIndex: 'link',
    },
    {
      title: '操作',
      render(text: string, record: BannerItem) {
        return (
          <Popconfirm
            title="删除任务"
            description="确定要删除了?"
            onConfirm={confirm(record.bannerid)}
            okText="是"
            cancelText="否"
          >
            <Button danger type="primary">
              删除
            </Button>
          </Popconfirm>
        );
      },
    },
  ];

  // useEffect(() => {
  //   getData();
  // }, []);

  const { data, error, loading } = useRequest(
    () => {
      return getData();
    },
    {
      refreshDeps: [count],
    },
  );

  // console.log(data);

  const confirm = (id: string) => async () => {
    const res = await removeBannerApi({ bannerid: id });
    if (res) {
      // message.success(res.message);
      messageApi.open({
        type: 'success',
        content: res.message,
      });
      // getData();
      setCount((count) => count + 1);
    }
  };

  const getData = async () => {
    const res = await getBannerApi();
    // console.log(res.data);
    return res;
    // if (res) {
    //   setDataSource(
    //     // res.data.map((item: any) => ({ ...item, key: item.bannerid })),
    //     res.data,
    //   );
    // }
  };

  return (
    <PageContainer
      ghost
      header={{
        title: '轮播图列表',
      }}
    >
      {contextHolder}
      {/* // rowKey是必须的，否则会报错，属性值会作为那条数据的唯一标识 */}
      {/* // dataSource是数据源，columns是表格的列 */}
      <Table
        dataSource={data}
        columns={columns}
        rowKey="bannerid"
        bordered
        loading={loading}
      />
    </PageContainer>
  );
};

export default Index;
